# 高级搜索功能数据模型
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import json


class SearchHistory(models.Model):
    """搜索历史模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    search_name = models.CharField(max_length=200, verbose_name="搜索名称")
    search_type = models.CharField(max_length=50, verbose_name="搜索类型")
    search_params = models.JSONField(default=dict, verbose_name="搜索参数")
    
    # 统计信息
    result_count = models.PositiveIntegerField(default=0, verbose_name="结果数量")
    execution_time = models.FloatField(default=0.0, verbose_name="执行时间(秒)")
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "搜索历史"
        verbose_name_plural = "搜索历史"
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', '-created_at']),
            models.Index(fields=['search_type', '-created_at']),
        ]
    
    def __str__(self):
        return f"{self.user.username} - {self.search_name}"


class SearchTemplate(models.Model):
    """搜索模板模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="创建人")
    name = models.CharField(max_length=200, verbose_name="模板名称")
    description = models.TextField(blank=True, verbose_name="模板描述")
    search_type = models.CharField(max_length=50, verbose_name="搜索类型")
    search_params = models.JSONField(default=dict, verbose_name="搜索参数")
    
    # 权限设置
    is_public = models.BooleanField(default=False, verbose_name="是否公开")
    shared_users = models.ManyToManyField(
        User, 
        related_name='shared_search_templates', 
        blank=True, 
        verbose_name="共享用户"
    )
    
    # 使用统计
    use_count = models.PositiveIntegerField(default=0, verbose_name="使用次数")
    last_used_at = models.DateTimeField(null=True, blank=True, verbose_name="最后使用时间")
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "搜索模板"
        verbose_name_plural = "搜索模板"
        ordering = ['-created_at']
        unique_together = ['user', 'name']
    
    def __str__(self):
        return self.name
    
    def increment_use_count(self):
        """增加使用次数"""
        self.use_count += 1
        self.last_used_at = timezone.now()
        self.save(update_fields=['use_count', 'last_used_at'])


class SavedSearch(models.Model):
    """保存的搜索模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    name = models.CharField(max_length=200, verbose_name="搜索名称")
    search_type = models.CharField(max_length=50, verbose_name="搜索类型")
    search_params = models.JSONField(default=dict, verbose_name="搜索参数")
    
    # 通知设置
    enable_notifications = models.BooleanField(default=False, verbose_name="启用通知")
    notification_frequency = models.CharField(
        max_length=20,
        choices=[
            ('daily', '每日'),
            ('weekly', '每周'),
            ('monthly', '每月'),
        ],
        default='weekly',
        verbose_name="通知频率"
    )
    
    # 最后执行信息
    last_executed_at = models.DateTimeField(null=True, blank=True, verbose_name="最后执行时间")
    last_result_count = models.PositiveIntegerField(default=0, verbose_name="最后结果数量")
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "保存的搜索"
        verbose_name_plural = "保存的搜索"
        ordering = ['-created_at']
        unique_together = ['user', 'name']
    
    def __str__(self):
        return f"{self.user.username} - {self.name}"
    
    def execute_search(self):
        """执行搜索"""
        from .views_search import advanced_search_service
        
        try:
            queryset = advanced_search_service.build_complex_query(
                self.search_type, 
                self.search_params
            )
            
            if queryset is not None:
                result_count = queryset.count()
                self.last_executed_at = timezone.now()
                self.last_result_count = result_count
                self.save(update_fields=['last_executed_at', 'last_result_count'])
                
                return {
                    'success': True,
                    'count': result_count,
                    'queryset': queryset
                }
            else:
                return {
                    'success': False,
                    'error': '无效的搜索参数'
                }
        except Exception as e:
            return {
                'success': False,
                'error': str(e)
            }


class SearchAlert(models.Model):
    """搜索预警模型"""
    CONDITION_CHOICES = [
        ('gt', '大于'),
        ('gte', '大于等于'),
        ('lt', '小于'),
        ('lte', '小于等于'),
        ('eq', '等于'),
        ('ne', '不等于'),
        ('change_gt', '变化大于'),
        ('change_lt', '变化小于'),
    ]
    
    saved_search = models.ForeignKey(SavedSearch, on_delete=models.CASCADE, verbose_name="关联搜索")
    name = models.CharField(max_length=200, verbose_name="预警名称")
    
    # 预警条件
    condition = models.CharField(max_length=20, choices=CONDITION_CHOICES, verbose_name="条件")
    threshold_value = models.IntegerField(verbose_name="阈值")
    
    # 通知设置
    notify_users = models.ManyToManyField(User, verbose_name="通知用户")
    email_enabled = models.BooleanField(default=True, verbose_name="邮件通知")
    sms_enabled = models.BooleanField(default=False, verbose_name="短信通知")
    
    # 状态
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    last_triggered_at = models.DateTimeField(null=True, blank=True, verbose_name="最后触发时间")
    trigger_count = models.PositiveIntegerField(default=0, verbose_name="触发次数")
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "搜索预警"
        verbose_name_plural = "搜索预警"
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name
    
    def check_condition(self, current_count, previous_count=None):
        """检查预警条件"""
        if self.condition == 'gt':
            return current_count > self.threshold_value
        elif self.condition == 'gte':
            return current_count >= self.threshold_value
        elif self.condition == 'lt':
            return current_count < self.threshold_value
        elif self.condition == 'lte':
            return current_count <= self.threshold_value
        elif self.condition == 'eq':
            return current_count == self.threshold_value
        elif self.condition == 'ne':
            return current_count != self.threshold_value
        elif self.condition == 'change_gt' and previous_count is not None:
            return abs(current_count - previous_count) > self.threshold_value
        elif self.condition == 'change_lt' and previous_count is not None:
            return abs(current_count - previous_count) < self.threshold_value
        
        return False
    
    def trigger_alert(self, current_count):
        """触发预警"""
        self.last_triggered_at = timezone.now()
        self.trigger_count += 1
        self.save(update_fields=['last_triggered_at', 'trigger_count'])
        
        # 发送通知
        self._send_notifications(current_count)
    
    def _send_notifications(self, current_count):
        """发送通知"""
        message = f"搜索预警 '{self.name}' 已触发，当前结果数量: {current_count}"
        
        # 这里可以集成邮件和短信发送服务
        # 暂时记录日志
        import logging
        logger = logging.getLogger(__name__)
        logger.info(f"搜索预警触发: {message}")


class QuickSearch(models.Model):
    """快速搜索配置模型"""
    name = models.CharField(max_length=200, verbose_name="搜索名称")
    description = models.TextField(blank=True, verbose_name="描述")
    search_type = models.CharField(max_length=50, verbose_name="搜索类型")
    search_params = models.JSONField(default=dict, verbose_name="搜索参数")
    
    # 显示设置
    icon = models.CharField(max_length=50, default='fas fa-search', verbose_name="图标")
    color = models.CharField(max_length=20, default='primary', verbose_name="颜色")
    order = models.PositiveIntegerField(default=0, verbose_name="排序")
    
    # 权限设置
    is_public = models.BooleanField(default=True, verbose_name="是否公开")
    allowed_groups = models.ManyToManyField(
        'auth.Group',
        blank=True,
        verbose_name="允许的用户组"
    )
    
    # 状态
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    
    # 统计信息
    use_count = models.PositiveIntegerField(default=0, verbose_name="使用次数")
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "快速搜索"
        verbose_name_plural = "快速搜索"
        ordering = ['order', 'name']
    
    def __str__(self):
        return self.name
    
    def increment_use_count(self):
        """增加使用次数"""
        self.use_count += 1
        self.save(update_fields=['use_count'])